package com.wms.handler;

import com.basis.utils.BaseServletHandler;
import com.mes.utils.ReturnSheetUtils;
import com.wms.entity.WmsStorageBatch;
import com.wms.entity.WmsStorageInOut;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.model.common.plm.Product;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StorageDetailsImportHandler extends BaseServletHandler {
	public static final String POSITIVE_INTEGER = "^\\d*[1-9]\\d*$";
	public static final String IS_NOT_NULL = "ISNOTNULL";
	public static final String IS_NUMBER = "ISNUMBER";
	private Product product = null;
	private Pattern p = Pattern.compile(POSITIVE_INTEGER);
	private Matcher m;

	@Override
	protected JSONObject service(HttpServletRequest request,HttpServletResponse response) {
		JSONObject result = ReturnSheetUtils.getSheet(request, response);
		JSONObject jsonRep = new JSONObject();
		String head_ID = request.getParameter("DataId");

		WmsStorageBatch wmsStorageBatch = OBDal.getInstance().get(WmsStorageBatch.class, head_ID);
		String message = "";
		
		try {
			if(result.getBoolean("flag")){
				Sheet sheet = (Sheet) result.get("sheet");
				//获取最后一行
				int lastLine = sheet.getLastRowNum();
				JSONObject obj = new JSONObject();
				for(int i = 1 ; i <= lastLine ; i++){
					obj = insertStorageMaterial(sheet.getRow(i), wmsStorageBatch);
					if(!obj.getBoolean("flag")){
						message += obj.getString("message");
						continue;
					}
				}
				
				if("".equalsIgnoreCase(message)){
					wmsStorageBatch.setStatus("OK");
					OBDal.getInstance().save(wmsStorageBatch);
					
					OBDal.getInstance().commitAndClose();
					jsonRep.put("desc", "导入成功，一共导入："+lastLine+"条数据。");
					jsonRep.put("result", true);
					return jsonRep;
				}else{
					jsonRep.put("desc", message);
					jsonRep.put("result", false);
					OBDal.getInstance().rollbackAndClose();
					return jsonRep;
				}
				
			}else{
				OBDal.getInstance().rollbackAndClose();
				jsonRep.put("desc", "导入失败。");
				jsonRep.put("result", false);
				return jsonRep;
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/**
	 * 插入数据库
	 * @param row
	 * @return
	 * @throws Exception 
	 */
	protected JSONObject insertStorageMaterial(Row row, WmsStorageBatch wmsStorageBatch) throws Exception{
		JSONObject result = new JSONObject();
		
		String materialCode = ReturnSheetUtils.readValue(row.getCell(0));
		String qty = ReturnSheetUtils.readValue(row.getCell(1));
		String desc = ReturnSheetUtils.readValue(row.getCell(3));
		
		if(!"".equalsIgnoreCase(materialCode)){
			product = getProduct(materialCode);
			if(product == null){
				result.put("flag", false);
				result.put("message", "物料编码为:"+materialCode+",的物料不存在，请仔细检查。");
				return result;
			}
		}else{
			result.put("flag", false);
			result.put("message", row.getRowNum()+"物料编码不能为空，请仔细检查。");
			return result;
		}
		
		
		if(!"".equalsIgnoreCase(qty)){
			boolean flag = isValidator(qty,IS_NUMBER);
			if(!flag){
				result.put("flag", false);
				result.put("message", "物料编码为:"+materialCode+"的数量值不正确，请仔细检查。");
				return result;
			}
		}else{
			result.put("flag", false);
			result.put("message", row.getRowNum()+"数量不能为空，请仔细检查。");
			return result;
		}

		WmsStorageInOut wsd  = new WmsStorageInOut();
		wsd.setQty(new BigDecimal(qty));
		wsd.setWmsStorageBatch(wmsStorageBatch);
		//wsd.setWarehouse(wmsStorageBatch.getWarehouse());//仓库
		//wsd.setLocator(wmsStorageBatch.getLocator());//线边库位
		wsd.setOptMode("");//出入库类型
		wsd.setProduct(product);
		wsd.setStatus("OK");
		wsd.setUom(product.getUOM());
		OBDal.getInstance().save(wsd);
		result.put("flag", true);
		return result;
	}

	/**
	 * 验证是数字
	 * @param value
	 * @return
	 */
	public boolean isValidator(String value,String type) {
		if(type.equalsIgnoreCase(IS_NOT_NULL)) {
			return false;
		} else if(type.equalsIgnoreCase(IS_NUMBER)) {
			m = p.matcher(value.trim());
			if (m.matches()){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}
	
	/**
	 * 获取物料
	 */
	public Product getProduct(String value){
		OBQuery query = OBDal.getInstance().createQuery(Product.class, " as mp where mp.searchKey = :value");
		query.setNamedParameter("value", value);
		return (Product)query.uniqueResult();
	}
}